﻿<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="title" width="600px" :minHeight="100" okText="确定" cancelText="取消" :showContinueBtn="showContinueBtn" :continueText="continueText" @ok="handleSubmit(0)" @continue="handleSubmit(1)" :closeFunc="onClose">
    <template #insertFooter>
      <a-space :size="10" v-if="dataForm.id" class="float-left">
      </a-space>
    </template>
    <a-row class="dynamic-form">
      <a-form :colon="false" layout="horizontal" labelAlign="right" :labelCol="{ style: { width: '100px' } }" :model="dataForm" :rules="dataRule" ref="formRef">
        <a-row :gutter="15">
          <a-col :span="24" class="ant-col-item" >
            <a-form-item name="code">
              <template #label>编号</template>
              <JnpfInput v-model:value="dataForm.code" placeholder="请输入" allowClear :style='{"width":"100%"}'  />
            </a-form-item>
          </a-col>
          <a-col :span="24" class="ant-col-item" >
            <a-form-item name="name">
              <template #label>名称</template>
              <JnpfInput v-model:value="dataForm.name" placeholder="请输入" allowClear :style='{"width":"100%"}'  />
            </a-form-item>
          </a-col>
          <a-col :span="24" class="ant-col-item" >
            <a-form-item name="address">
              <template #label>地址</template>
              <JnpfInput v-model:value="dataForm.address" placeholder="请输入" allowClear :style='{"width":"100%"}'  />
            </a-form-item>
          </a-col>
          <a-col :span="24" class="ant-col-item" >
            <a-form-item name="tel">
              <template #label>电话</template>
              <JnpfInput v-model:value="dataForm.tel" placeholder="请输入" allowClear :style='{"width":"100%"}'  />
            </a-form-item>
          </a-col>
          <a-col :span="24" class="ant-col-item" >
            <a-form-item name="comment">
              <template #label>说明备注</template>
              <JnpfInput v-model:value="dataForm.comment" placeholder="请输入" allowClear :style='{"width":"100%"}'  />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-row>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { create, update, getInfo } from './helper/api';
  import { reactive, toRefs, nextTick, ref, unref, computed, toRaw} from 'vue';
  import { BasicModal, useModal } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useUserStore } from '/@/store/modules/user';
  import type { FormInstance } from 'ant-design-vue';
  import { thousandsFormat } from '/@/utils/jnpf';
  import { getTimeUnit, getDateTimeUnit } from '/@/utils/jnpf';
  import dayjs from 'dayjs';

  interface State {
    dataForm: any;
    dataRule: any;
    title: string;
    continueText: string;
    allList: any[];
    currIndex: number;
    isContinue: boolean;
    submitType: number;
    showContinueBtn: boolean;
  }

  const emit = defineEmits(['reload']);
  const userStore = useUserStore();
  const userInfo = userStore.getUserInfo;
  const { createMessage, createConfirm } = useMessage();
  const [registerModal, { openModal, setModalProps }] = useModal();
  const formRef = ref<FormInstance>();
  const state = reactive<State>({
    dataForm: {
      id: '',
      code: undefined,
      name: undefined,
      address: undefined,
      tel: undefined,
      comment: undefined,
    },
    dataRule: {
      code: [
        {
          required: true,
          message: '请输入编号',
          trigger: 'blur',
        },
      ],
      name: [
        {
          required: true,
          message: '请输入名称',
          trigger: 'blur',
        },
      ],
    },
    title: '',
    continueText: '',
    allList: [],
    currIndex: 0,
    isContinue: false,
    submitType: 0,
    showContinueBtn: true,
  });
  const { title, continueText, showContinueBtn, dataForm, dataRule } = toRefs(state);

  const getPrevDisabled = computed(() => state.currIndex === 0);
  const getNextDisabled = computed(() => state.currIndex === state.allList.length - 1);

  defineExpose({ init });

  function init(data) {
    state.showContinueBtn = false;
    state.title = !data.id ? '新增' : '编辑';
    state.continueText = !data.id ? '确定并新增' : '确定并继续';
    setFormProps({ continueLoading: false });
    state.dataForm.id = data.id;
    openModal();
    state.allList = data.allList;
    state.currIndex = state.allList.length && data.id ? state.allList.findIndex((item) => item.id === data.id) : 0;
    nextTick(() => {
      getForm().resetFields();
      setTimeout(initData, 0);
    });
  }
  function initData() {
    changeLoading(true);
    if (state.dataForm.id) {
      getData(state.dataForm.id);
    } else {
      // 设置默认值
      state.dataForm={
        code: undefined,
        name: undefined,
        address: undefined,
        tel: undefined,
        comment: undefined,
      };
      changeLoading(false);
    }
  }
  function getForm() {
    const form = unref(formRef);
    if (!form) {
      throw new Error('form is null!');
    }
    return form;
  }
  function getData(id) {
    getInfo(id).then((res) => {
      state.dataForm = res.data || {};
      changeLoading(false);
    });
  }
  async function handleSubmit(type) {
    try {
      const values = await getForm()?.validate();
      if (!values) return;
      state.submitType = type;
      state.submitType === 1 ? setFormProps({ continueLoading: true }) : setFormProps({ confirmLoading: true });
      const formMethod = state.dataForm.id ? update : create;
      formMethod(state.dataForm)
        .then((res) => {
          createMessage.success(res.msg);
          state.submitType === 1 ? setFormProps({ continueLoading: false }) : setFormProps({ confirmLoading: false });
          if (state.submitType == 1) {
            initData();
            state.isContinue = true;
          } else {
            setFormProps({ visible: false });
            emit('reload');
          }
        })
        .catch(() => {
          state.submitType === 1 ? setFormProps({ continueLoading: false }) : setFormProps({ confirmLoading: false });
        });
    } catch (_) {}
  }
  function handlePrev() {
    state.currIndex--;
    handleGetNewInfo();
  }
  function handleNext() {
    state.currIndex++;
    handleGetNewInfo();
  }
  function handleGetNewInfo() {
    changeLoading(true);
    getForm().resetFields();
    const id = state.allList[state.currIndex].id;
    getData(id);
  }
  function setFormProps(data) {
    setModalProps(data);
  }
  function changeLoading(loading) {
    setModalProps({ loading });
  }
  async function onClose() {
    if (state.isContinue) emit('reload');
    return true;
  }
  function getParamList(templateJson, formData, index?) {
    for (let i = 0; i < templateJson.length; i++) {
      if (templateJson[i].relationField) {
        //区分是否子表
        if (templateJson[i].relationField.includes('-')) {
          let tableVModel = templateJson[i].relationField.split('-')[0]
          let childVModel = templateJson[i].relationField.split('-')[1]
          templateJson[i].defaultValue = formData[tableVModel] && formData[tableVModel][index] && formData[tableVModel][index][childVModel] || ''
        } else {
          templateJson[i].defaultValue = formData[templateJson[i].relationField] || ''
        }
      }
    }
    return templateJson
  }
</script>
